package com.yisoo.ubag.product.service.impl;

import com.yisoo.common.utils.R;
import com.yisoo.ubag.product.entity.ConsumerEntity;
import com.yisoo.ubag.product.entity.DevSecBraConEntity;
import com.yisoo.ubag.product.service.BrandService;
import com.yisoo.ubag.product.service.ConsumerService;
import com.yisoo.ubag.product.service.SceneService;
import com.yisoo.ubag.product.util.TokenMd5Util;
import com.yisoo.ubag.product.vo.DevTokenTableVo;
import com.yisoo.ubag.product.vo.UsedTokenVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yisoo.common.utils.PageUtils;
import com.yisoo.common.utils.Query;

import com.yisoo.ubag.product.dao.DevTokenDao;
import com.yisoo.ubag.product.entity.DevTokenEntity;
import com.yisoo.ubag.product.service.DevTokenService;
import org.springframework.util.StringUtils;


@Service("devTokenService")
public class DevTokenServiceImpl extends ServiceImpl<DevTokenDao, DevTokenEntity> implements DevTokenService {

    @Autowired
    ConsumerService consumerService;

    @Autowired
    BrandService brandService;
    @Autowired
    SceneService sceneService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DevTokenEntity> page = this.page(
                new Query<DevTokenEntity>().getPage(params),
                new QueryWrapper<DevTokenEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCid(Map<String, Object> params, Long cid) {
        String key = (String) params.get("key");
        Integer pageSize = Integer.valueOf((String)params.get("limit"));
        Integer currPage = Integer.valueOf((String)params.get("page"));

        QueryWrapper<DevTokenEntity> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            queryWrapper.eq("run_token",key);
        }
        queryWrapper.eq("master_id",cid);

        List<DevTokenEntity> entityList = baseMapper.selectList(queryWrapper);
        List<DevTokenTableVo> collect = entityList.stream().map(temp -> {
            DevTokenTableVo tableVo = new DevTokenTableVo();
            BeanUtils.copyProperties(temp, tableVo);
            //如果不可用，就不要解析了
            if(String.valueOf(temp.getBrandId()).equals("-1")){
                return tableVo;
            }
            tableVo.setBrandName(brandService.getById(temp.getBrandId()).getBrandName());
            tableVo.setSceneName(sceneService.getById(temp.getSceneId()).getSceneName());
            return tableVo;
        }).collect(Collectors.toList());
        /**
         * 分页
         * @param list        列表数据
         * @param totalCount  总记录数
         * @param pageSize    每页记录数
         * @param currPage    当前页数
         */
//    public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
        return new PageUtils(collect,collect.size(),pageSize,currPage);
    }

    @Override
    public void clearByIds(List<String> asList) {
        for (String token :
                asList) {
            DevTokenEntity entity = this.getById(token);
            entity.setEnable(0);
            entity.setBrandId(Long.parseLong("-1"));
            entity.setSceneId(Long.parseLong("-1"));
            entity.setTokenUsing(-1);
            this.updateById(entity);
        }
    }

    @Override
    public R generator(DevTokenEntity devToken, int i) {

        //检查能否生成这么多
        ConsumerEntity consumerEntity = consumerService.getById(devToken.getMasterId());
        Integer limitCount = consumerEntity.getCount();
        QueryWrapper<DevTokenEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("master_id",devToken.getMasterId());
        int haveCount = this.count(queryWrapper);

        if(haveCount+i >limitCount){
            return R.error("token数量超限");
        }

        List<DevTokenEntity> list = new ArrayList<>();
        DevTokenEntity temp;
        for (int index = 0;index<i;index++){
                temp = new DevTokenEntity();
                BeanUtils.copyProperties(devToken,temp );
                temp.setRunToken(TokenMd5Util.getSimpleToken(devToken.getMasterId()));
                list.add(temp);
//            System.out.println("[][]"+temp);
        }
//        System.out.println("===========================");
        this.saveBatch(list);
        return R.ok();
    }

    @Override
    public R countUsed(Long cid) {

        ConsumerEntity consumerEntity = consumerService.getById(cid);
        Integer limitCount = consumerEntity.getCount();
        QueryWrapper<DevTokenEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("master_id",cid);
        int haveCount = this.count(queryWrapper);
        String str = "已经使用:"+haveCount+"  总共："+limitCount;
        return R.ok().put("data",new UsedTokenVo(haveCount*100/limitCount,str));

    }

    //查出这些条件的所有token
    @Override
    public List<DevTokenEntity> getCountByCidBidSid(Long consumerId, Long brandId, Long sceneId) {
        QueryWrapper<DevTokenEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("master_id",consumerId)
                .eq("brand_id",brandId)
                .eq("scene_id",sceneId);
        List<DevTokenEntity> devTokenEntities = baseMapper.selectList(queryWrapper);
        return devTokenEntities;
    }



}